package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;

import com.itheima.reggie.common.R;
import com.itheima.reggie.common.BaseContest;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Value("${nologin.url}")
    private String urlPaths;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //登录相关的请求都应该放行
        // /employee/login /employee/logout 及静态页面资源 /backend/** /front/**
        String requestURI = request.getRequestURI();
        AntPathMatcher matcher =new AntPathMatcher();
        //String[] patterns = new String[]{"/employee/login","/employee/logout","/backend/**","/front/**"};
        String[] patterns = urlPaths.split(",");
        for (String pattern : patterns) {
            boolean match = matcher.match(pattern, requestURI);
            if(match){
                chain.doFilter(request,servletResponse);
                return;
            }
        }
        //判断用户是否登录，如果登录了，放行
        //判断依据
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if(employee != null){
            BaseContest.setCurrentId(employee.getId());
            chain.doFilter(request,servletResponse);
            //释放threadLocal的空间,避免内存溢出
            BaseContest.removeCurrentId();
            return;
        }
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if(loginUser != null){
            BaseContest.setCurrentId(loginUser.getId());
            chain.doFilter(request,servletResponse);
            //释放threadLocal的空间,避免内存溢出
            BaseContest.removeCurrentId();
            return;
        }
        //如果没有登录，拦截
        //返回数据 R code:0 msg:NOTLOGIN data:null
        R<Object>  r = R.error("NOTLOGIN");
        String toJSON =  JSON.toJSONString(r);
        servletResponse.getWriter().write(toJSON);
    }
}


